package www.dianbaozu.com.ui.chat.addFriend

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.netease.nim.uikit.api.NIMRepository
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import www.dianbaozu.com.R
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString

class AddFriendViewModel @ViewModelInject constructor(private val appDataManager: AppDataManager) :
    BaseViewModel() {

    val nickName = MutableLiveData("")

    /**
     * 根据昵称搜索用户
     */
    @FlowPreview
    fun searchUserByNickName(
        nickName: String,
        action: ((Result.Success<UseInfoEntity>) -> Unit)
    ) {
        viewModelScope.launch {
            appDataManager.searchUserByNickNameFlow(nickName)
                .retryWhen { cause, attempt ->
                    return@retryWhen cause.message == "网络异常" && attempt <= 1
                }
                .onStart {
                    loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                            "",
                            LoadingDialogStateType.LOADING
                        )
                    )
                }
                .onCompletion { cause ->
                    if (cause == null) {
                        loading.value = UiStateCustom(
                            stateData = LoadingDialog(
                                tip = "",
                                loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                isShowDialogTip = false,
                                isShowToastTip = true
                            )
                        )
                    }
                }
                .catch { cause ->
                    loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                            tip = cause.message ?: "网络异常",
                            loadingDialogStateType = LoadingDialogStateType.ERROR,
                            isShowDialogTip = false,
                            isShowToastTip = true
                        )
                    )
                }
                .collect {
                    action.invoke(it)
                }
        }
    }


}